<template>
  <view class="login-page">
    <!-- 顶部背景图片盒子 -->
    <view class="login-bg-top">
      <image src="/static/img/topBg.png" mode="widthFix" class="bg-img" />
    </view>
    <view class="login-content" :class="{ 'fade-out': loggingIn }">
      <view class="login-title">欢迎使用安电司！</view>
      <view class="login-subtitle">我们致力守护每一度电的安全</view>
      <view class="login-form">
        <input v-model="mobile" :disabled="loggingIn" placeholder="请输入手机号" class="login-input" maxlength="11" type="number" />
        <input v-model="password" :disabled="loggingIn" :type="showPwd ? 'text' : 'password'" placeholder="输入密码" class="login-input pwd-input" maxlength="20" />
        <view class="eye-icon" @click="onEyeClick">
          <image :src="showPwd ? '/static/img/open-view.png' : '/static/img/close-view.png'" class="eye-img" mode="widthFix" />
        </view>
      </view>
    </view>
    <view class="login-btn-wrapper" :class="{ 'login-animating': loggingIn }">
      <button
        class="login-btn"
        @click="login"
        :disabled="loggingIn"
      >
        <span>{{ loggingIn ? '正在登录...' : '登录' }}</span>
      </button>
    </view>
    <view class="login-protocol" :class="{ 'fade-out': loggingIn }">
      <view class="protocol-row">
        <view class="checkbox-border circle">
          <tn-checkbox v-model="checked" :disabled="loggingIn" size="sm" active-color="#1ec8e1" inactive-color="#bbb" checked-shape="circle" />
        </view>
        <text>我已阅读并同意</text>
        <text class="protocol-link" @click="!loggingIn && mygo('/pages/minePages/userAgreement')">《用户协议》</text>
        <text>和</text>
        <text class="protocol-link" @click="!loggingIn && mygo('/pages/minePages/privacyPolicy')">《隐私协议》</text>
      </view>
    </view>

    <view class="register-link" :class="{ 'fade-out': loggingIn } " @click="mygo('/pages/register')">
      还没有账号？立即注册
    </view>
    <!-- 底部背景图片盒子 -->
    <view class="login-bg-bottom">
      <image src="/static/img/bottomBg.png" mode="widthFix" class="bg-img" />
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue';
import { useGlobalStore } from '@/store/app';
import { mygo } from '@/utils/useNavigator';
import { createRequest } from '@/utils/request';
import { 
  validatePhone, 
  validatePassword,
  showValidationError 
} from '@/utils/validators';

const mobile = ref('');
const password = ref('');
const showPwd = ref(false);
const checked = ref(false);
const store = useGlobalStore();
const loggingIn = ref(false)

let eyeTimer = null;



function onEyeClick() {
  if (loggingIn.value) return;
  showPwd.value = true;
  if (eyeTimer) clearTimeout(eyeTimer);
  eyeTimer = setTimeout(() => {
    showPwd.value = false;
    eyeTimer = null;
  }, 4000);
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (eyeTimer) {
    clearTimeout(eyeTimer);
    eyeTimer = null;
  }
});

const login = async () => {
  // 使用封装的验证函数
  if (!showValidationError(validatePhone(mobile.value))) {
    return;
  }
  if (!showValidationError(validatePassword(password.value, '密码'))) {
    return;
  }
  if (!checked.value) {
    uni.showToast({ title: '请先同意协议', icon: 'none' });
    return;
  }
  
  loggingIn.value = true;
  
  try {
    // 向后端发送登录请求
    const requestData = {
      mobile: mobile.value,
      password: password.value
    };
    const response = await createRequest('/auth/login', {
      method: 'POST',
      data: requestData
    });
    // 权限映射关系
    const permissionMapping = {
      accountManagePermission: 'account',
      addNewMonitorPermission: 'addNew',
      alertPermission: 'audit',
      blackListPermission: 'blacklist',
      exportPermission: 'report',
      keyDevicePermission: 'dev1ce',
      publicAreaPermission: 'public',
      screenPermission: 'screen'
    };
    
    // 根据权限信息生成模块列表
    const modules = [];
    const permissionInfo = response.data.permissionInfo;
    
    Object.keys(permissionMapping).forEach(permissionKey => {
      if (permissionInfo[permissionKey]) {
        modules.push(permissionMapping[permissionKey]);
      }
    });
    
    // 映射用户信息到store格式
    const userInfo = {
      mobile: response.data.userInfo.mobile,
      token: response.data.accessToken,
      userId: response.data.userInfo.userId,
      nickname: response.data.userInfo.realName,
      avatar: response.data.userInfo.avatarUrl,
      role: response.data.userInfo.userType === 1 ? 'offsite' : 'onsite', // 1=非现场
      modules: modules
    };

    // 获取公司信息
    try {
      const companyInfo = await createRequest('/user/info/lite');
      if (companyInfo.data && companyInfo.data.tenantName) {
        userInfo.department = companyInfo.data.tenantName;
      }
    } catch (companyError) {
      console.warn('获取公司信息失败:', companyError);
    }
    // 保存用户信息到store（包含区域数据获取）
    await store.setUserInfo(userInfo);
    // 动画持续 500ms 后执行登录逻辑
    setTimeout(() => {
        // 页面跳转
        uni.reLaunch({ url: '/pages/index' });

    }, 500);

  } catch (error) {
    console.error('error', error);
    loggingIn.value = false;
    
    // 处理不同的错误情况
    let errorMessage = '登录失败';
    if (error.response && error.response.data && error.response.data.msg) {
      errorMessage = error.response.data.msg;
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    uni.showToast({ 
      title: errorMessage, 
      icon: 'none' 
    });
  }
};

</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  width: 100vw;
  background: #172869;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8rpx 48rpx 0 rgba(30,60,114,0.18);
}
.login-content {
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 280rpx 48rpx 0 48rpx;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
}
.login-title {
  font-size: 60rpx;
  color: #fff;
  margin-bottom: 8rpx;
  text-align: left;
  letter-spacing: 2rpx;
}
.login-subtitle {
  font-size: 28rpx;
  font-weight: 400;
  color: #e0e6f6;
  margin-bottom: 64rpx;
  text-align: left;
}
.login-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  margin-top: 200rpx;
  position: relative;
}
.login-input {
  width: 100%;
  border: none;
  border-bottom: 2rpx solid #b3d6f7;
  font-size: 32rpx;
  padding: 18rpx 0 18rpx 0;
  background: transparent;
  color: #fff;
  margin-bottom: 0;
  outline: none;
  transition: border-color 0.2s;
}
.login-input::placeholder {
  color: #b3d6f7;
  opacity: 1;
}
.pwd-input {
  margin-bottom: 0;
}
.eye-icon {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: 0;
  bottom: 10%;
}
.eye-img {
  width: 40rpx;
  height: 40rpx;
  display: block;
}
.login-btn-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  margin: 80rpx 0 0 0;
  transition: transform 0.6s cubic-bezier(0.4,0,0.2,1);
}
.login-btn-wrapper.login-animating {
  transform: translateY(-200rpx);
}
.login-btn {
  width: 660rpx;
  padding: 0;
  height: 80rpx;
  background: linear-gradient(135deg, rgba(79, 210, 255, 0.9) 0%, rgba(58, 141, 222, 0.9) 50%, rgba(79, 210, 255, 0.9) 100%);
  backdrop-filter: blur(40rpx);
  -webkit-backdrop-filter: blur(40rpx);
  color: #fff;
  border: none;
  border-radius: 100rpx;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 12rpx 32rpx 0 rgba(30, 200, 225, 0.18);
  letter-spacing: 2rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.login-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    135deg,
    transparent 0%,
    rgba(79, 210, 255, 0.2) 10%,
    rgba(79, 210, 255, 0.4) 25%,
    rgba(79, 210, 255, 0.6) 40%,
    rgba(79, 210, 255, 0.7) 50%,
    rgba(68, 175, 238, 0.6) 60%,
    rgba(58, 141, 222, 0.4) 75%,
    rgba(58, 141, 222, 0.2) 90%,
    transparent 100%
  );
  animation: metalShine 4s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;
  z-index: 1;
}

.login-btn span {
  position: relative;
  z-index: 2;
}

@keyframes metalShine {
  0% {
    left: -100%;
    opacity: 0;
  }
  20% {
    opacity: 1;
  }
  80% {
    opacity: 1;
  }
  100% {
    left: 100%;
    opacity: 0;
  }
}
.login-protocol {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 64rpx;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
  flex-wrap: wrap;
  z-index: 10;
}
.protocol-row {
  display: flex;
  align-items: center;
}
.checkbox-border.circle {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #4fd2ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12rpx;
  box-sizing: border-box;
}
.protocol-link {
  color: #4fd2ff;
  margin: 0 4rpx;
}
.fade-out {
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.5s;
}


.register-link {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 200rpx;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
  z-index: 10;
}
.login-bg-top {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 416rpx;
  z-index: 0;
  pointer-events: none;
}
.login-bg-bottom {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  height: 120rpx;
  z-index: 0;
  pointer-events: none;
}
.bg-img {
  width: 100vw;
  height: 100%;
  object-fit: cover;
  display: block;
}
</style> 
